import React, { Component } from 'react';
import { tryConvert } from './common';
import BoilingVerdict from './BoilingVerdict';
import TemperaturInput from './TemperaturInput';

export default class TemperatureCalculator extends Component {
  constructor() {
    super();

    this.state = {
      temperature: '',
      scale: 'Celsius'
    };
  }

  handleTemperatureChange(data, scale) {
    this.setState({
      temperature: data,
      scale: scale
    });
  }

  render() {
    const scale = this.state.scale;
    const temperature = this.state.temperature;
    const celsiusVal = scale === 'Fahrenheit' ? tryConvert(temperature, 'Celsius') : temperature;
    const fahrenheitVal = scale === 'Celsius' ? tryConvert(temperature, 'Fahrenheit') : temperature;
    return (
      <div className='temperature-calculator'>
        <TemperaturInput scale='Celsius' temperature={ celsiusVal } onTemperatureChange={ (data) => { this.handleTemperatureChange(data, 'Celsius'); } }></TemperaturInput>
        <TemperaturInput scale='Fahrenheit' temperature={ fahrenheitVal } onTemperatureChange={ (data) => { this.handleTemperatureChange(data, 'Fahrenheit'); } }></TemperaturInput>
        <BoilingVerdict celsius={ parseFloat(celsiusVal) }></BoilingVerdict>
      </div>
    )
  }
}
